package com.allianz.webapps.controllers;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.allianz.frame.utils.AESUtil;
import com.allianz.frame.utils.PropertiesUtil;
import com.allianz.webapps.https.interfaces.type001.pojo.User;
import com.allianz.webapps.https.interfaces.util.ObjectUtil;
import com.fasterxml.jackson.databind.ObjectMapper;

import net.sf.json.JSONObject;

@Controller
@RequestMapping(value="login")
public class LoginController {
	
	@Autowired
	private ObjectMapper objectMapper;
	@Autowired
	private ObjectUtil objectUtil;
	
	private final String cKey="XPJpMaHM0XIu1PgN";
	
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	//http://localhost:8080/pad_marketing/login/index.action
	@RequestMapping(value="login")
	@ResponseBody
	public Map<String,Object> inde(@RequestParam(value="jsonParam")String jsonParam,String toUrl,HttpServletRequest request,HttpServletResponse response) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String validateC = (String) request.getSession().getAttribute("validateCode");
		String path = PropertiesUtil.getProperty("domain");
		boolean flag = false;
		if((!"http://localhost:9000".equals(path)  && !"http://dev.allianz.com.cn/".equals(path))
		&& !"http://portal.allianz.com.cn/".equals(path) || "https://pts.allianz.com.cn/".equals(path)) {
			flag = true;
		}
		String verify;
		//待验证码的User
		User user=objectMapper.readValue(jsonParam,User.class);	
		String body=objectUtil.requestParam(user, "user.login");
		//得到传来的验证码
		verify=user.getVerify();		
		JSONObject json = JSONObject.fromObject(body);	
		//后台报错
		if("F".equals(json.get("Status"))){
			map.put("ErrMsg", json.get("ErrMsg")); 
			return map;
		}		
		//前台报错
		if(flag && !verify.equalsIgnoreCase(validateC))
		{
			map.put("ErrMsg","验证码不正确");
			return map;
		}	
		//成功登陆 设置session username
		if(json.get("Body")!=null){
			JSONObject js = JSONObject.fromObject(json.get("Body"));
			User u = (User) JSONObject.toBean(js, User.class);		
			request.getSession().setAttribute("username",u);	
		}
		String DeString = "/pad_marketing/index/index.action";
		if ( toUrl==null || "null".equals(toUrl) || "".equals(toUrl)) {
			DeString = "/pad_marketing/index/index.action";
			map.put("Url", DeString);
		}else{
			toUrl=toUrl.replaceAll(" ", "+");
			DeString = AESUtil.Decrypt(toUrl, cKey);
				map.put("Url", DeString);
		}
		return map;
	}
	
	@RequestMapping(value="index")
	public String index(HttpServletRequest request,HttpServletResponse response){
		return "views/page/login";
	}
	
	@RequestMapping(value="timeout")
	public ModelAndView sessionTimeOut(HttpServletRequest request,HttpServletResponse response){
		Map<String,String> map = new HashMap<String,String>();
		map.put("message", "session超时");
		return new ModelAndView("forward:/pad_marketing/views/page/login.html",map);
	}
	
	
	@RequestMapping("/loginOut")//注销
	@ResponseBody
    public Map<String,Object> loginOut(@RequestParam(value="jsonParam")String jsonParam,HttpServletRequest request,HttpServletResponse response) throws IOException{
     
        Map<String,Object> map = new HashMap<String, Object>();
		//设置用户对象到session中
		request.getSession().removeAttribute("username");
		map.put("url", request.getContextPath()+"/login/index.action");
		return map;
    }
	
	@RequestMapping("createCode")//生成动态码
	@ResponseBody
    public Map<String,Object> createCode(@RequestParam(value="jsonParam")String jsonParam,HttpServletRequest request,HttpServletResponse response) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		//拿到后台验证码
		String validateC = (String) request.getSession().getAttribute("validateCodeTwo");
		
		User user=objectMapper.readValue(jsonParam,User.class);
		String verify =user.getVerify();    //验证码
		if(!verify.equalsIgnoreCase(validateC)){
			map.put("codeErrMsg", "验证码错误");
			return map;
		}
		String body=objectUtil.requestParam(user, "user.sendSMSVerifyCode");
		map.put("result", body);
       return map;
    }
	
	@RequestMapping(value="getTel")
	@ResponseBody
	public String getTel(@RequestParam(value="jsonParam") String jsonParam,HttpServletRequest request,HttpServletResponse response)
			throws Exception{
		Object obj=objectMapper.readValue(jsonParam,Object.class);
		String body=objectUtil.requestParam(obj, "user.getMobile");
		return body;
	}
	
	@RequestMapping(value="changePassword")
	@ResponseBody
	public String changePassword(@RequestParam(value="jsonParam")String us,HttpServletRequest request,HttpServletResponse response)
			throws Exception{
		User user=objectMapper.readValue(us,User.class);
		String body=objectUtil.requestParam(user, "user.changePwd");
		return body;
	}
	
	@RequestMapping(value="check-login")
	@ResponseBody
	public Map<String,Object> check_login(String toUrl,HttpServletRequest request) throws Exception{
		Map<String,Object> map = new HashMap<String, Object>();
		User user = (User)request.getSession().getAttribute("username");
		if (user != null) {
			String DeString = "";
			if ( toUrl==null || "null".equals(toUrl) || "".equals(toUrl)) {
				DeString = "/pad_marketing/index/index.action";
				map.put("Url", DeString);
			}else{
				DeString = AESUtil.Decrypt(toUrl, cKey);
					map.put("Url", DeString);
			}
			map.put("status", "success");
		}else{
			map.put("status", "fail");
		}
		return map;
		}
	}